package com.licq.ldoc.writer.visitor.structure;

import org.apache.commons.lang.StringUtils;

import com.licq.ldoc.domain.Attribute;
import com.licq.ldoc.domain.Element;
import com.licq.ldoc.utils.LowAgieUtils;
import com.licq.ldoc.writer.Writer;
import com.licq.ldoc.writer.visitor.Visitor;
import com.lowagie.text.Anchor;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Table;

public class StructureVisitor implements Visitor {
    private final Table table;
    
    public StructureVisitor(Table table) {
        this.table = table;
    }

    public void visit(Element element) throws BadElementException {
        table.addCell(LowAgieUtils.createHCell(String.valueOf(element.getLevel()), 
        		Cell.ALIGN_CENTER));
        table.addCell(LowAgieUtils.createCell(
        		(element.getLevel() == 0 ? "" : "@") + element.getName(), 
        		true
        	)
        );
        table.addCell(createType(element));
        table.addCell(LowAgieUtils.createHCell(
        		element.getOccurrences().toString(),
        		Cell.ALIGN_CENTER
        	)
        );
        table.addCell(LowAgieUtils.createHCell(element.isRequired() ? "Y" : "N", 
        		Cell.ALIGN_CENTER));
        table.addCell(LowAgieUtils.createCell(element.getComments()));
        for (Attribute attribute : element.getAttributes()) {
            attribute.accept(this);
        }
        for (Element subElement : element.getAttributeElements()) {
            subElement.accept(this);
        }
    }

    public void visit(Attribute attribute) throws BadElementException {
        table.addCell(StringUtils.EMPTY);
        table.addCell(LowAgieUtils.createCell("@" + attribute.getName()));
        table.addCell(LowAgieUtils.createCell(attribute.getType().getLabel()));
        table.addCell(LowAgieUtils.createHCell(
        		attribute.getOccurrences().toString(), 
        		Cell.ALIGN_CENTER
        	)
        );
        table.addCell(LowAgieUtils.createHCell(attribute.isRequired() ? "Y" : "N", 
        		Cell.ALIGN_CENTER));
        table.addCell(LowAgieUtils.createCell(attribute.getComments()));
    }
     
    private Cell createType(Element element) throws BadElementException {
    	Cell cell = null;
    	String type = element.getType().getLabel();
		if (!Writer.isInternalAnchorEnabled() || (!element.hasAnchor() && !element.hasLink())) {
    		cell = LowAgieUtils.createCell(type, true);
    	} else if (element.hasAnchor()) {
    		Anchor anchor = LowAgieUtils.createAnchor(type, true);
    		anchor.setName(element.getAnchor());
    		cell = new Cell(anchor);
    	} else if (element.hasLink()) {
    		Anchor link = LowAgieUtils.createLink(type, true);
    		link.setReference(element.getAnchor());
    		cell = new Cell(link);
    	}
    	return cell;
	}

}
